package com.jufanshare.myblog.service.comment;

import com.jufanshare.myblog.common.dto.AjaxRes;
import com.jufanshare.myblog.dao.ArticleDao;
import com.jufanshare.myblog.entity.Article;
import com.jufanshare.myblog.entity.Comment;
import com.jufanshare.myblog.entity.User;
import com.jufanshare.myblog.service.base.BaseServiceImpl;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * 作用：
 * 作者：Tiddler
 * 时间：2019/1/23 20：03
 * 类名： FriendUrlServiceImpl
 **/
@Service
public class CommentServiceImpl extends BaseServiceImpl<Comment> implements CommentService {
    @Autowired
    private SQLManager sqlManager;
    @Autowired
    private ArticleDao articleDao;
    @Transactional
    @Override
    public AjaxRes webComment(Comment comment, HttpSession session) {
        AjaxRes res=new AjaxRes();
        if(comment.getCommenttext().length()>=500){
            res.setFailMsg("抱歉，字数不得大于500");
            return res;
        }
        User sessionUser = (User) session.getAttribute("web_userlogin_session");
        if(sessionUser==null){
            res.setFailMsg("请先登录");
            return res;
        }
        Comment findEntity=new Comment();
        findEntity.setUserid(sessionUser.getId());
        findEntity.setArticleid(comment.getArticleid());
        long count = templateCount(findEntity);
        if(count>=2){
            res.setFailMsg("抱歉，每个用户最多只能对此文章评论两次，如果无法描述清楚，请加入QQ群交流。");
            return res;
        }
        comment.setHeadImg(sessionUser.getHeadimg());
        comment.setCommenttext(HtmlUtils.htmlEscape(comment.getCommenttext()));//过滤掉评论内容中的可转义符号
        comment.setCommentdatetime(new Date());
        comment.setCommentstate("正常");
        comment.setNickname(sessionUser.getNickname());
        comment.setUserid(sessionUser.getId());
        insert(comment,true);
        Article article=new Article();
        article.setId(comment.getArticleid());
        articleDao.commentNumberAdd(article);
        res.setRes(true);
        res.setObj(comment);
        return res;
    }

    @Override
    public PageQuery<Comment> webByPage(Comment t, PageQuery<Comment> pageQuery) {
        pageQuery.setParas(t);
        PageQuery<Comment> commentPageQuery = sqlManager.pageQuery("comment.webByPage", Comment.class, pageQuery);
        return commentPageQuery;
    }
}
